<template>
  <div class="login">
    <a-form class="login-form" @submit.prevent="doLogin" :autoFormCreate="(form) => this.form = form" :style="{'flex-direction': isMobile ? 'column' : 'row', 'width': isMobile ? '90vw' : '700px'}">
      <div class="form-lf">
        <div class="form-title" style="padding:0 30px;">郑州大学研究生教育支撑平台</div>
        <img src="@/assets/login/graduation.jpg" alt="">
      </div>
      <div class="form-rg">
        <!-- <div class="form-title">欢迎回来</div> -->
        <a-menu v-model="current" mode="horizontal" class="type_title" >
            <a-menu-item key="1"> 用户登录 </a-menu-item>
            <a-menu-item key="2" @click="getQr()"> 微信登录 </a-menu-item>
            <a-menu-item key="4"> 单点登录</a-menu-item>
        </a-menu>
        <div :class="current[0] == '2' ? 'menu_iphone_login' : (current[0] == '3' ? 'menu_qr_login' : 'menu_iphone_login')" @click="loginType()"></div>
        <template v-if="current[0] == '1'">
            <a-form-item
              fieldDecoratorId="name"
              :fieldDecoratorOptions="{rules: [{ required: true, message: '请输入用户名', whitespace: true}]}">
              <a-input size="large" placeholder="用户名/邮箱账号">
                <img slot="prefix" style="width: 16px" src="@/assets/login/user.png" alt="">
              </a-input>
            </a-form-item>
            <a-form-item
              fieldDecoratorId="password"
              :fieldDecoratorOptions="{rules: [{ required: true, message: '请输入密码', whitespace: true}]}">
              <a-input size="large" type="password" placeholder="密码">
                <img slot="prefix" style="width: 16px" src="@/assets/login/pwd.png" alt="">
              </a-input>
            </a-form-item>
            <a-form-item fieldDecoratorId="yzm" :fieldDecoratorOptions="{rules: [{ required: true, message: '请输入验证码', whitespace: true}]}">
              <a-input style="width: 55%;margin-right: 20px" placeholder="请输入验证码" />
              <img style="width: 80px" :src="'data:image/jpeg;base64,' +captcha.img" alt="">
            </a-form-item>
        </template>

        <template v-if="current[0] == '2' && qrUrl">
            <img class="qr" :src="'data:image/jpeg;base64,' + qrUrl" >
        </template>

        <template  v-if="current[0] == '3'">
          <a-form-item fieldDecoratorId="mobile"
                       :fieldDecoratorOptions="{rules: [{ required: true, message: '请输入正确的手机号', pattern: /^1[3456789]\d{9}$/ }]}">
            <a-input size="large" placeholder="11 位手机号">
              <a-icon slot="prefix" type="phone"/>
            </a-input>
          </a-form-item>

            <a-row :gutter="8">
              <a-col :span="12">
                <a-form-item fieldDecoratorId="yzm"  :fieldDecoratorOptions="{rules: [{ required: true, message: '请输入验证码', whitespace: true}]}">
                  <a-input size="large" type="text" placeholder="验证码">
                      <a-icon slot="prefix" type="profile" />
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-button
                  size="large"
                  class="getCaptcha"
                  :disabled="state.smsSendBtn"
                  @click.stop.prevent="getMobileCaptcha"
                  v-text="!state.smsSendBtn && '获取验证码'||(state.time+' s')"></a-button>
              </a-col>
            </a-row>
        </template>
        <template v-if="current[0] == '4'">
          <a-button @click="toOutLoginStudent">单点登录-学生端</a-button>
          <a-button @click="toOutLoginTeacher">单点登录-教师端</a-button>

        </template>
        <template v-if="current[0] != '4'">
          <a-radio-group :options="plainOptions" :default-value="userType" @change="typeChange"/>
          <template>
            <a-checkbox style="margin-top:10px" @change="hwchange">
              海外虚拟研究生
            </a-checkbox>
          </template>
          <a @click="passwordVisible = true" style="margin:10px 0 0;display:block">找回密码</a>
          <a target="_blank" style="color: red" href="http://gs.ha.edu.cn/postgrad-server">河南省云服务管理平台</a>
          <a-button v-if="current[0] != '2'" :loading="loading"
                    style="width: 100%; margin-top: 10px;border-radius: 10px!important" size="large" htmlType="submit"
                    type="primary">
            登录
          </a-button>

        </template>
        <!--<div class="form-rg-ft"> <span>科研平台</span> <span>云平台管理员</span> </div>-->
      </div>
    </a-form>

    <retrieve-password :visible="passwordVisible" :userType="userType" @close="passwordVisible = false"/>
    <force-update-password
      :token="token"
      @success="handleUpdate"
      @cancel="handleCancelUpdate"
      :updatePasswordModelVisible="forceUpdatePasswordVisule">
    </force-update-password>
  </div>

</template>

<script>
  import {mapMutations, mapState} from 'vuex'
  import retrievePassword from './retrievePassword'
  import forceUpdatePassword from '../personal/forceUpdatePassword'

  const plainOptions = [
    {label: '管理端', value: 'SYSTEM'},
    {label: '学生端', value: 'STUDENT'},
    {label: '教师端', value: 'TEACHER'},
  ]
  export default {
    name: 'Login',
    data() {
    return {
      plainOptions,
      current: ['1'],
      loading: false,
      error: '',
      activeKey: '1',
      captcha: {},
      passwordVisible: false,
      forceUpdatePasswordVisule: false,
      token: '',
      state: {
        time: 60,
        smsSendBtn: false
      },
      qrUrl: '',
      timer: null,
      userType: "SYSTEM",
      isVirtual: false //海外虚拟研究生
    }
    },
    components: {forceUpdatePassword, retrievePassword},
    watch: {
      current() {
        clearInterval(this.timer)
      },
    },
    computed: {
      systemName() {
        return this.$store.state.setting.systemName
      },
      copyright() {
      return this.$store.state.setting.copyright
    },
    ...mapState({
      isMobile: state => state.setting.isMobile
    }),
  },
  created () {
    this.getCaptcha()
    this.$db.clear()
    this.$router.options.routes = []
  },
  methods: {
    hwchange(e){
      this.isVirtual = e.target.checked
    },
    typeChange(e){
      this.userType = e.target.value
      if(this.current[0] == '2'){
        clearInterval(this.timer)
        this.getQr()
      }
    },
    loginType(item,key){
      if( this.current[0] == '2' || this.current[0] == '1'){
          this.current = ['3']
      }else{
        this.getQr()
        this.current = ['2']
      }
    },
    getCaptcha() {
      this.$api.auth.getCaptcha().then(res => {
        this.captcha = {...res.data }
        this.$nextTick(() => {
          this.form.setFieldsValue({
            uuid: res.data.uuid
          });
        })
      })
    },
    getMobileCaptcha (e) {
      e.preventDefault()
      let that = this
      this.form.validateFields(['mobile'], {force: true},(err, values) => {
          if (!err) {
            let mobile = this.form.getFieldValue('mobile')
            //这边走获取验证码接口
            this.$api.auth.getSms({sjh : mobile, userType : this.userType}).then(res => {
              this.$message.success(res.msg)
            })
            this.state.smsSendBtn = true
            let interval = window.setInterval(() => {
              if (that.state.time-- <= 0) {
                that.state.time = 60
                that.state.smsSendBtn = false
                window.clearInterval(interval)
              }
            }, 1000)
          }
        }
      )
    },
    getQr(){
      this.$api.auth.getQr({userType:this.userType}).then(res => {
        this.qrUrl = res.data.img
        this.wxLoginCheck(res.data.token)
      })
    },
    wxLoginCheck(token){
      let _this = this
      this.timer = setInterval( () =>{
          _this.$api.auth.loginCheck({token}).then(res => {
            if(res.msg == '登录成功'){
              clearInterval(this.timer)
              if(this.userType == 'SYSTEM'){
                this.getUser(res.token)
              }else if(this.userType == 'STUDENT'){
                window.location.href = `${process.env.USER_TYPE_STUDENT}#/login?token=${res.token}`
              }else{
                window.location.href = `${process.env.USER_TYPE_TEACHER}#/login?token=${res.token}`
              }

            }else if(res.msg != '未登录！'){
              clearInterval(this.timer);
              _this.$message.warning(res.msg);
            }

          }).catch((err) => {
            console.log(err)
              clearInterval(this.timer)
          })
      },3000)

    },
    doLogin () {
      if (this.current[0] == '1') {
        // 用户名密码登录
        this.form.validateFields(['name', 'password', 'yzm'], (errors, values) => {
          if (!errors) {
            this.loading = true
            let name = this.form.getFieldValue('name')
            let password = this.form.getFieldValue('password')
            // password = this.$Base64.encode(password)
            password = this.$Base64.encode(password)
            this.$api.auth.commonLogin({
              ...values,
              username: name,
              password: password,
              xxdm: 10459,
              loginType: this.current[0] == '1' ? 'ACCOUNT' : (this.current[0] == '2' ? 'WECHAT' : 'MOBILE'),
              userType: this.userType,
              uuid: this.captcha.uuid,
              isVirtual: this.isVirtual
            }).then((r) => {
              // return
              clearInterval(this.timer)
              this.loading = false
              if (r.isRewrite) {
                this.forceUpdatePasswordVisule = true;
                this.token = r.token;
              } else {
                if (this.userType == 'SYSTEM') {
                  this.getUser(r.token)
                } else if (this.userType == 'STUDENT') {

                  if (r.token) {
                    window.location.href = `${process.env.USER_TYPE_STUDENT}#/login?token=${r.token}`
                  }
                } else {
                  if (r.token) {
                    window.location.href = `${process.env.USER_TYPE_TEACHER}#/login?token=${r.token}`
                  }
                }
              }


            }).catch((e) => {

              this.getCaptcha()
              setTimeout(() => {
                this.loading = false
              }, 500)
            })
          }
        })
      }
      if (this.current[0] === '3') {
        // 手机验证码登录
        this.form.validateFields(['mobile', 'yzm'], (errors, values) => { // 验证码接口地址
          if (!errors) {
            this.loading = true
            let mobile = this.form.getFieldValue('mobile')
            let yzm = this.form.getFieldValue('yzm')
            this.$api.auth.commonLogin({
              username: mobile,
              yzm: yzm,
              password: 1,
              loginType: this.current[0] == '1' ? 'ACCOUNT' : (this.current[0] == '2' ? 'WECHAT' : 'MOBILE'),
              userType: this.userType,
              uuid: this.captcha.uuid
            }).then((r) => {
              if(this.userType == 'SYSTEM'){
                this.getUser(r.token)
              }else if(this.userType == 'STUDENT'){
                window.location.href = `${process.env.USER_TYPE_STUDENT}#/login?token=${r.token}`
              }else{
                window.location.href = `${process.env.USER_TYPE_TEACHER}#/login?token=${r.token}`
              }
            }).catch(() => {
              setTimeout(() => {
                this.loading = false
              }, 500)
            })
          }
        })
      }
    },
    toOutLoginStudent() {
      let targetUrl = Base64.encode("http://gs2.zzu.edu.cn/stu/#/login");
      let studentUrl = encodeURI('http://gs2.zzu.edu.cn/api/common/cas/login/STUDENT?');
      let finalUrl = "https://cas.s.zzu.edu.cn/cas/login?service=" + studentUrl + "targetUrl=" + targetUrl;
      window.location.href = finalUrl;
    },

    toOutLoginTeacher() {
      let targetUrl = Base64.encode("http://gs2.zzu.edu.cn/tea/#/login");
      let studentUrl = encodeURI('http://gs2.zzu.edu.cn/api/common/cas/login/TEACHER?');
      // let targetUrl = Base64.encode("http://tea.ezmate.cn/#/login");
      // let studentUrl = encodeURI('http://service.ezmate.cn/api/common/cas/login/TEACHER?');
      //  let targetUrl=Base64.encode("http://localhost:8083/#/login");
      //  let studentUrl=encodeURI('http://localhost:8081/api/common/cas/login/TEACHER?');
      let finalUrl = "https://cas.s.zzu.edu.cn/cas/login?service=" + studentUrl + "targetUrl=" + targetUrl;
      window.location.href = finalUrl;
    },
    getUser(token) {
      this.$api.auth.commonGetUser(token).then(r => {
        let data = r.data
        this.saveLoginData(data)
        this.$api.menu.findByUserId(data.user.id).then((res) => {
          const asyncRouter = res.data
          localStorage.setItem('USER_ROUTER', JSON.stringify(asyncRouter))
          this.$router.push('/')
        })
        setTimeout(() => {
          this.loading = false
        }, 500)
      })
    },
    regist () {
      this.$emit('regist', 'Regist')
    },
    // getCaptcha () {
    //   this.$message.warning('暂未开发')
    // },
    handleTabsChange (val) {
      this.activeKey = val
    },
    ...mapMutations({
      setToken: 'account/setToken',
      setExpireTime: 'account/setExpireTime',
      setPermissions: 'account/setPermissions',
      setRoles: 'account/setRoles',
      setUser: 'account/setUser',
      setTheme: 'setting/setTheme',
      setLayout: 'setting/setLayout',
      setMultipage: 'setting/setMultipage',
      fixSiderbar: 'setting/fixSiderbar',
      fixHeader: 'setting/fixHeader',
      setColor: 'setting/setColor'
    }),
    saveLoginData (data) {
      this.setToken(data.token)
      this.setExpireTime(data.exipreTime)
      this.setPermissions(data.permissions)
      this.setUser(data.user)
      this.setRoles(data.roles)
      this.setTheme(data.config.theme)
      this.setLayout(data.config.layout)
      this.setMultipage(data.config.multiPage === '1')
      this.fixSiderbar(data.config.fixSiderbar === '1')
      this.fixHeader(data.config.fixHeader === '1')
      this.setColor(data.config.color)
    },
    updatePassword() {
      this.forceUpdatePasswordVisule = true
    },
    handleCancelUpdate() {
      this.forceUpdatePasswordVisule = false
    },
    handleUpdate() {
      this.forceUpdatePasswordVisule = false
      this.$message.success('更新密码成功，请重新登录系统')
      setTimeout(() => {
        this.logout()
      }, 1500)
    },
    logout() {
      this.$api.auth.logout().then(() => {
        return new Promise((resolve, reject) => {
          this.$db.clear()
          location.reload()
        })
      }).catch(() => {
        this.$message.error('退出系统失败')
      })
    },
  }
}
</script>

<style lang="less" scoped>
  .type_title{
    margin-bottom: 20px;
  }
  .qr{
    width: 150px;
    height: 150px;
    display: block;
    margin: 0 auto 50px;
  }
  .ant-menu-item{
    padding: 0 30px !important;
  }
  .menu_iphone_login{
    width: 40px;
    height: 40px;
    background-image: url(https://img.t.sinajs.cn/t6/style/images/growth/login/sprite_login.png?a4d8ba1a862aead3);
    background-repeat: no-repeat;
    background-position: 0px -150px;
    position: absolute;
    right: 0;
    top: 7px;
    animation:myfirst 0.2s;
    &:hover{
        cursor: pointer;
    }
  }
  .menu_qr_login{
    width: 40px;
    height: 40px;
    background-image: url(https://img.t.sinajs.cn/t6/style/images/growth/login/sprite_login.png?a4d8ba1a862aead3);
    background-repeat: no-repeat;
    background-position: -40px -190px;
    position: absolute;
    right: 0;
    top: 7px;
    animation:myfirst2 0.2s;
    &:hover{
        cursor: pointer;
    }
  }
  @keyframes myfirst{
    from {background-position: -40px -190px;}
    to {background-position: 0px -150px;}
  }
  @keyframes myfirst2{
    from {background-position: 0px -150px;}
    to {background-position: -40px -190px;}
  }
  .form-rg{
    width: 260px;
    position: relative;
  }
  .login-form{
    background-color: #fff;
    padding: 30px;
    display: flex;
    width: 700px;
    margin: 0 auto;
    .form-title{
      font-size: 30px;
      text-align: center;
      margin: 30px 0;
    }
    .form-lf{
      margin-right: 100px;
      width: 280px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    .form-rg-ft{
      color: #c5c5c5;
      display: flex;
      justify-content: space-between;
      width: 120%;
      position: relative;
      left: -10%;
      margin: 30px 0;
      span:before{
        content: "";
        display: inline-block;
        width: 10px;
        height: 10px;
        background-color: #c5c5c5;
        border-radius: 50%;
        margin-right: 20px;
      }
    }
  }
</style>
